const http = require("http");
const fs = require("fs");
const path = require("path");
const urlMoudle = require("url");
const server = http.createServer();
const mimeTypes = {
  css: "text/css;charset=utf-8",
  jpg: "image/jpeg",
  html: "text/html;charset=utf-8",
};
server.on("request", function (req, res) {
  //获取资源路径
  //1.通过路由来识别请求的资源文件在哪
  //看懂路由  http://127.0.0.1/product.html
  let url = urlMoudle.parse(req.url).pathname;
  if (url == "/") {
    //读取响应的静态资源内容
    //本身路径一定要传绝对路径
    fs.readFile(
      path.join(__dirname, "static/index.html"),
      "utf-8",
      function (err, data) {
        if (err) {
          console.log(err);
        } else {
          //读取静态资源文件响应给浏览器
          res.setHeader("Content-Type", mimeTypes["html"]);
          res.end(data);
        }
      }
    );
  } else if (url == "/product.html") {
    fs.readFile(
      path.join(__dirname, "static/product.html"),
      "utf-8",
      function (err, data) {
        if (err) {
          console.log(err);
        } else {
          res.setHeader("Content-Type", mimeTypes["html"]);
          res.end(data);
        }
      }
    );
  } else if (url == "/css/main.css") {
    const cssPath = path.join(__dirname, "static/css/main.css");
    fs.readFile(cssPath, "utf-8", function (err, data) {
      if (err) {
        console.log(err);
      } else {
        res.setHeader("Content-Type", mimeTypes["css"]);
        res.end(data);
      }
    });
  } else if (url == "/images/pro-1.jpg") {
    const imgPath = path.join(__dirname, "static/images/pro-1.jpg");
    fs.readFile(imgPath, function (err, data) {
      if (err) {
        console.log(err);
      } else {
        res.setHeader("Content-Type", mimeTypes["jpg"]);
        res.end(data);
      }
    });
  } else if (url == "/images/pro-2.jpg") {
    const imgPath = path.join(__dirname, "static/images/pro-2.jpg");
    fs.readFile(imgPath, function (err, data) {
      if (err) {
        console.log(err);
      } else {
        res.setHeader("Content-Type", mimeTypes["jpg"]);
        res.end(data);
      }
    });
  } else if (url == "/images/pro-3.jpg") {
    const imgPath = path.join(__dirname, "static/images/pro-3.jpg");
    fs.readFile(imgPath, function (err, data) {
      if (err) {
        console.log(err);
      } else {
        res.setHeader("Content-Type", mimeTypes["jpg"]);
        res.end(data);
      }
    });
  } else {
    fs.readFile(
      path.join(__dirname, "static/404.html"),
      "utf-8",
      function (err, data) {
        if (err) {
          console.log(err);
        } else {
          res.setHeader("Content-Type", mimeTypes["html"]);
          res.end(data);
        }
      }
    );
  }
});
server.listen(3000, function () {
  console.log("listen port 3000...");
  console.log("http://127.0.0.1:3000");
});
